<script setup lang="ts">
import { ref } from 'vue'
// import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'

defineProps({
  imageUrl: {
    type: String,
    default: ''
  }
})
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imageFormat = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
  if (!imageFormat.includes(rawFile.type)) {
    ElMessage.error('上传头像图片只能是JPG、PNG、GIF、BMP格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 选择图片后触发
const uploadImage = (params: any) => {
  console.log(params)
}
</script>

<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
